package tmi.li.txwthr;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import tmi.li.txwthr.R;


public class TxWthrConfiguration extends Activity implements Runnable {
	static final String TAG = "tmi.li.txwthr.TxWthrConfiguration";
	public Woeid w = new Woeid();
	private ProgressDialog pd;
	private String woeid = "";
	private String city = "";
	private String hex = "";
	private String bhex = "";
	private String format = "c";
	private String appname ="";
	private CharSequence[] appNames;
	private long timestamp;
	private TextView text;
	private Thread thread;
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	
	public TxWthrConfiguration() {
		super();
	}

	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		Log.d(TAG, "onCreate()");

		// Set the result to CANCELED.  This will cause the widget host to cancel
		// out of the widget placement if they press the back button.
		setResult(RESULT_CANCELED);
		// Set the view layout resource to use.
		setContentView(R.layout.appwidget_configure);

		// Find the EditText
		//mAppWidgetPrefix = (EditText)findViewById(R.id.appwidget_prefix);
		
		//fill the SPinner with the languages
		Spinner s = (Spinner) findViewById(R.id.language);
		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter = ArrayAdapter.createFromResource(
	            this, R.array.lang, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s.setAdapter(adapter);
		
		
		// Bind the action for the save button.
		findViewById(R.id.selectapp).setOnClickListener(mAppClickListener);
		findViewById(R.id.save).setOnClickListener(mSaveOnClickListener);
		findViewById(R.id.woeid).setOnClickListener(mCityOnClickListener);
		final RadioButton c = (RadioButton) findViewById(R.id.cel);
		final RadioButton f = (RadioButton) findViewById(R.id.fahr);
		c.setOnClickListener(radio_listener);
		f.setOnClickListener(radio_listener);
		// Find the widget id from the intent. 
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		// If they gave us an intent without the widget id, just bail.
		if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
	}

	//menu dialog for picking a app
	public void openAppMenu() {
		//IntentCategorys
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);;
		//Init Lists
		@SuppressWarnings("rawtypes")
		final List AppList = getPackageManager().queryIntentActivities(mainIntent, 0);
		//final CharSequence[] appPackageNames = new CharSequence[AppList.size()];
		appNames = new CharSequence[AppList.size()];
		final ResolveInfo[] appInfos =  new ResolveInfo[AppList.size()];
		int i = 0;
		//Get appnames and packagenames
		for (Object item:  getPackageManager().queryIntentActivities( mainIntent, 0)) {
			appInfos[i] = (ResolveInfo)item;
			appNames[i] = getPackageManager().getApplicationLabel(appInfos[i].activityInfo.applicationInfo);
			i++;
		}

		//Create dialog.builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick a app");
		builder.setItems(appNames, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Toast.makeText(getApplicationContext(), "selected App: "+appNames[item], Toast.LENGTH_SHORT).show();	
				appname = appInfos[item].activityInfo.packageName.toString()+"/"+appInfos[item].activityInfo.name.toString();
				text = (TextView)findViewById(R.id.appname);
				text.setText(appNames[item]);			}
		});

		//Create dialog with builder
		AlertDialog alert = builder.create();

		//Display dialog
		alert.show();
	}

	//menu dialog for picking a city
	public void openMenu() {
		int length = w._woeid.size();
		
		
		//if only one city was found, end it without opening a menu
		if(length == 1) {
			woeid = w._woeid.get(0).split(",")[0];
			text = (TextView)findViewById(R.id.many);
			text.setText(w._woeid.get(0)+ ", "+ w.getDesc(0));
			
			
		}else if(length > 1){ // if more then one city was found, fill a array with city name + country 
			final CharSequence[] items = new CharSequence[length];
			for(int i = 0; i < length; i++) {
				items[i] = w.getDesc(i);
			}
			
			//Initialize the Menu and implement the onclicklistener
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Pick the most likely result");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {		 
					Toast.makeText(getApplicationContext(), "selected: "+items[item], Toast.LENGTH_SHORT).show();
					text = (TextView)findViewById(R.id.many);
					text.setText(items[item]);
					woeid = w._woeid.get(item);
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	//onclick listener for AppSelector DIalog
	View.OnClickListener mAppClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//final Context context = AppWidgetConfigure.this;
			
			//saving the city name in the var city & starting the thread 
			openAppMenu();
		}
	};


	//onclick listener for getWoeid button
	View.OnClickListener mCityOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//final Context context = AppWidgetConfigure.this;
			
			//saving the city name in the var city & starting the thread 
			text = (TextView)findViewById(R.id.city);
			city = text.getText().toString();
			thread = new Thread(TxWthrConfiguration.this);
			pd = ProgressDialog.show(TxWthrConfiguration.this, "Updating", "Getting Woeid for ur City...", true,false);	
			try { 
				thread.start();   
			}catch(Exception e) {
				pd.dismiss();
				Toast.makeText(getApplicationContext(), "Error occured, try again", Toast.LENGTH_SHORT).show();
			}
		}
	};

	
	//onclick Listener for the save Dialog
	View.OnClickListener mSaveOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			final Context context = TxWthrConfiguration.this;
			
			//getting the Font Color and background color
			EditText text = (EditText)findViewById(R.id.color);
			hex = text.getText().toString();
			text = (EditText)findViewById(R.id.bcolor);
			bhex = text.getText().toString();
			
			
			//if no city was selected notificate the user
			if(woeid != "") {
				try { 
					
					//trying to set the FontColor/Background Color, if it fails
					//the user used a wrong color code
					TextView colortest = (TextView)findViewById(R.id.TextView09);
					colortest.setTextColor(Color.parseColor(hex));
					colortest.setTextColor(Color.parseColor(bhex));
					
					if(appname == "")  throw new InterruptedException();
					
					//saving the languages
					Spinner s = (Spinner) findViewById(R.id.language);
					String test = (String) s.getSelectedItem();
					test = specLang(test);
					
					//returning the result
					Intent resultValue = new Intent();
					resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
					setResult(RESULT_OK, resultValue);
					
					//saving the id and preferences of the newly created widget
					TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXWTHR);
					txpref.savePrefs(context, mAppWidgetId, ""+bhex+";"+hex+";"+woeid+";"+format);
					txpref.saveId(context, mAppWidgetId);
					txpref.saveLang(context, mAppWidgetId, test);
					txpref.saveAppName(context, mAppWidgetId, appname);
					
					
					//updating the widget and destroying the Thread
					AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
					TxWthrProvider.updateWidget(context, appWidgetManager, mAppWidgetId);
					thread = null;
					finish();
				}catch(InterruptedException a) {
					Toast.makeText(getApplicationContext(), "no App selected !!", Toast.LENGTH_LONG).show();
				}catch(Exception e) {
					Toast.makeText(getApplicationContext(), "Wrong Color code !!", Toast.LENGTH_LONG).show();
				}
			}else {
				Toast.makeText(getApplicationContext(), "No City selected !!", Toast.LENGTH_LONG).show();
			}

		}
	};

	
	
	//onclick listener for the radio buttons ( format celcius or fahrenheit ) 
	View.OnClickListener radio_listener = new View.OnClickListener() {
		public void onClick(View v) {
			// Perform action on clicks
			RadioButton rb = (RadioButton) v;
			if(rb.getText().toString().contains("F")){        	
				format="f";
			}else {
				format="c";
			}
		}
	};
	
	
	
	//getting the right Lang String
	public String specLang(String lang) {
		if(compareString(lang, "Eng"))
			return "en";
		if(compareString(lang, "Fre"))
			return "fr";
		if(compareString(lang, "Ru"))
			return "ru";
		if(compareString(lang, "Ger"))
			return "de";
		return "null";
	}
	
	public boolean compareString(String orig, String cmp) {
		int orig_size = orig.length();
		int cmp_size = cmp.length();
		String orig_up = orig.toLowerCase();
		String orig_down = orig.toUpperCase();
		int b = 0;
		for(int i = 0; i < orig_size; i++) {
			if(orig.charAt(i) == cmp.charAt(b) || orig_up.charAt(i) == cmp.charAt(b) || orig_down.charAt(i) == cmp.charAt(b)) {
				b++;
				if(b == cmp_size)return true;
				continue;
			}
			else {
				if(orig_size - i < cmp_size) return false;
				if(b != 0) b = 0;
				continue;
			}
			
		}
		
		return false;
		
	}
	
	
	//the Thread used for getting the woeid
	//thread tries every second to get the woeid until 15 seconds
	//then the thread will break and the user will get the message that no wifi connection
	//could be established
	
	public void run() {
		boolean t = false; 
		//timestamp when we first try to get the woeid
		timestamp = System.currentTimeMillis();
		
		//try and try and try...
		while(!t) {
			if(t = w.getRss(city)) {
				//if the getRss was successful break the loop and send a message to the handler
				handler.sendEmptyMessage(0);	
				break;
			}
			//set the thread to sleep 1 second
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				handler.sendEmptyMessage(1);	
			}
			
			//if 15 seconds did pass without getting the woeid once, break the loop and send a message to the handler
			if(System.currentTimeMillis() - timestamp > 15000){
				handler.sendEmptyMessage(1);	
				break;
			}
		}
	}

	//handler used to notify user when thread was successful 
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			//if thread was successful then dismiss the progress dialog and open the menu
			if(!msg.equals(1)) 	{
				pd.dismiss();
				openMenu();
				
				//FIXME
				try {
					thread = null;
				}catch(Exception e) {
					Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
				}
				
			}else { // notify the user that no connection could be established
					Toast.makeText(getApplicationContext(), "Couldnt connect to Woeid webservice", Toast.LENGTH_LONG).show();
			}
		}
	};    

}
